iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 19

[Day19] Codewars >>> Calculating with Functions (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

A perfect power is a classification of positive integers:

In mathematics, a perfect power is a positive integer that can be expressed as an >integer power of another positive integer. More formally, n is a perfect power if there >exist natural numbers m > 1, and k > 1 such that mk = n.

Your task is to check wheter a given integer is a perfect power. If it is a perfect >power, return a pair m and k with mk = n as a proof. Otherwise return Nothing, Nil, >null, NULL, None or your language's equivalent.

Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so >(3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a >number is a perfect power, return any pair that proves it.

Examples
isPP(4) => [2,2]
isPP(9) => [3,2]
isPP(5) => None

解題思路

題目理解:設計一函式代入n,若其存在兩整數m&k可使m^k = n則返還(m,k)。
這裡可以使用math.log(n, i)來找到對數k,示例如下:

import math
def isPP(n):
    #找尋潛在底數時因最小可能存在對數為2,故對數最大範圍找到本身的平方根即可
    for i in range(2, int(math.sqrt(n))+1):
        #利用math.log()找出底數為i時,n的對數為times_of_sqrt
        times_of_sqrt = round(math.log(n, i))
        if i ** times_of_sqrt == n:
            return [i, times_of_sqrt]
    return None

上一篇
[Day18] Codewars >>> Probabilities for Sums in Rolling Cubic Dice (Python)
下一篇
[Day20] Codewars >>> Integers: Recreation One (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言